package com.butterfly.hotkey.core.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONFactory;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.reader.ObjectReader;
import com.alibaba.fastjson2.writer.ObjectWriter;
import com.alibaba.fastjson2.writer.ObjectWriterPrimitiveImpl;

import java.lang.reflect.Type;
import java.util.concurrent.atomic.LongAdder;

/**
 * 封装fastjson，统一掉系统内所有的序列化
 *
 * @author butterfly
 * @since 2024/10/19
 */
public class FastJsonUtil {

    static {
        JSON.register(String.class, new ObjectWriterPrimitiveImpl<String>() {
            @Override
            public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features) {
                jsonWriter.writeRaw((String) object);
            }
        });

        // 注册自定义序列化器
        JSONFactory.getDefaultObjectWriterProvider().register(LongAdder.class, new LongAdderSerializer());

        // 注册自定义反序列化器
        JSONFactory.getDefaultObjectReaderProvider().register(LongAdder.class, new LongAdderDeserializer());
    }

    private static final JSONWriter.Feature[] FEATURES = {
            JSONWriter.Feature.WriteMapNullValue,
            JSONWriter.Feature.WriteNullListAsEmpty,
            JSONWriter.Feature.WriteNullNumberAsZero,
            JSONWriter.Feature.WriteNullBooleanAsFalse,
            JSONWriter.Feature.WriteNullStringAsEmpty
    };

    public static String toJsonStr(Object object) {
        return JSON.toJSONString(object, FEATURES);
    }

    public static <T> T parseObject(String json, Class<T> clazz) {
        return JSON.parseObject(json, clazz);
    }

    public static class LongAdderSerializer implements ObjectWriter<LongAdder> {

        @Override
        public void write(JSONWriter writer, Object object, Object fieldName, Type fieldType, long features) {
            LongAdder longAdder = (LongAdder) object;
            writer.writeInt64(longAdder.longValue());
        }
    }

    public static class LongAdderDeserializer implements ObjectReader<LongAdder> {

        @Override
        public LongAdder readObject(JSONReader reader, Type fieldType, Object fieldName, long features) {
            LongAdder longAdder = new LongAdder();
            longAdder.add(reader.readInt64());
            return longAdder;
        }
    }
}
